package com.ym.fc.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ym.fc.bean.Collection;
import com.ym.fc.common.Constants;
import com.ym.fc.dao.CollectionDao;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author yanm
 * @date 2021/1/7 15:46
 **/
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CollectionService {

    private final CollectionDao collectionDao;

    private final RedisTemplate redisTemplate;

    private int add(Collection collection) {
        return collectionDao.insert(collection);
    }

    private List<Collection> list(Collection collection) {
        Wrapper wrapper = new QueryWrapper<Collection>(collection);
        return collectionDao.selectList(wrapper);
    }

    private Collection queryCollection(Long id) {
        return collectionDao.selectById(id);
    }

    public int deleteById(Long id) {
        return collectionDao.deleteById(id);
    }

    public String createTaskNum(String userId) {
        String num = "";
        while (num == "" || redisTemplate.opsForSet().isMember(Constants.TASKNUM, num) == false) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            num = userId + dateFormat.format(new Date());
            byte[] bytes = DigestUtils.md5Digest(num.getBytes(StandardCharsets.UTF_8));
            num = new String(bytes);
        }
        redisTemplate.opsForSet().add(Constants.COLLECTNUM, num);
        return num;
    }

    public String createCollectNum(String userId) {
        String num = "";
        while (num == "" || redisTemplate.opsForSet().isMember(Constants.COLLECTNUM, num) == false) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            num = userId + dateFormat.format(new Date());
            byte[] bytes = DigestUtils.md5Digest(num.getBytes(StandardCharsets.UTF_8));
            num = new String(bytes);
        }
        redisTemplate.opsForSet().add(Constants.COLLECTNUM, num);
        return num;
    }



}
